package thinkingInJava.containers;

import static thinkingInJava.YTool.YPrint.println;

//: containers/TypesForSets.java
//Methods necessary to put your own type in a Set.
import java.util.*;

class SetType {
int i;
public SetType(int n) { i = n; }
public boolean equals(Object o) {
 return o instanceof SetType && (i == ((SetType)o).i);
}
public String toString() { return Integer.toString(i); }
}

class HashType extends SetType {
public HashType(int n) { super(n); }
public int hashCode() { return i; }
}

class TreeType extends SetType
implements Comparable<TreeType> {
public TreeType(int n) { super(n); }
//public int hashCode() { return i; } 定义后放入 Set 中才不会重复
public int compareTo(TreeType arg) {	// 注意与 equals 一致，如 equals为 true 时  compareTo 必须返回0，反之返回非0
 return (arg.i < i ? -1 : (arg.i == i ? 0 : 1));
 // 这里不能用 return i-arg.i; 因为有可能会溢出如 i是大的正整数， arg.i 是很大的负数，结果为负。
 // 只有无符号数溢出才不会有问题，但 Java 没有无符号数
// 溢出例：
// 	Byte bb = Byte.MAX_VALUE;
//	Byte dd = Byte.MIN_VALUE;
//	Byte re = (byte)(bb-dd);
//	println((int)re); 输出 -1
}
}

public class TypesForSets {
static <T> Set<T> fill(Set<T> set, Class<T> type) {
 try {
   for(int i = 0; i < 10; i++)
       set.add(
         type.getConstructor(int.class).newInstance(i));	// 代表要调用含有一个 int.class 参数的构造函数
 } catch(Exception e) {
   throw new RuntimeException(e);
 }
 return set;
}
static <T> void test(Set<T> set, Class<T> type) {
 fill(set, type);
 fill(set, type); // Try to add duplicates
 fill(set, type);
 System.out.println(set);
}
public static void main(String[] args) {
 test(new HashSet<HashType>(), HashType.class);
 test(new LinkedHashSet<HashType>(), HashType.class);
 test(new TreeSet<TreeType>(), TreeType.class);
 // Things that don't work: 下面的 set 都会重复，因为缺少hashCode（使用了默认的） 
 test(new HashSet<SetType>(), SetType.class);
 test(new HashSet<TreeType>(), TreeType.class);
 test(new LinkedHashSet<SetType>(), SetType.class);
 test(new LinkedHashSet<TreeType>(), TreeType.class);
 try {
   test(new TreeSet<SetType>(), SetType.class);
 } catch(Exception e) {
   System.out.println(e.getMessage());
 }
 try {
   test(new TreeSet<HashType>(), HashType.class);
 } catch(Exception e) {
   System.out.println(e.getMessage());
 }
}
} /* Output: (Sample)
[2, 4, 9, 8, 6, 1, 3, 7, 5, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[9, 9, 7, 5, 1, 2, 6, 3, 0, 7, 2, 4, 4, 7, 9, 1, 3, 6, 2, 4, 3, 0, 5, 0, 8, 8, 8, 6, 5, 1]
[0, 5, 5, 6, 5, 0, 3, 1, 9, 8, 4, 2, 3, 9, 7, 3, 4, 4, 0, 7, 1, 9, 6, 2, 1, 8, 2, 8, 6, 7]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
java.lang.ClassCastException: SetType cannot be cast to java.lang.Comparable
java.lang.ClassCastException: HashType cannot be cast to java.lang.Comparable
*///:~

